<?php
/**
 * Classe di utilita' per le entity
 *
 * @author Damiano Ciarla
 * @version 1.0
 * @category lib/entity
 */
class EntityUtils
{
	/**
	 * Istanza della classe
	 */
	private static $istance = null;

	/**
	 * Restituisce l'istanza della classe EntityUtils qualora questa fosse già
	 * stata istanziata altrimenti ne viene creata una nuova e viene restituita.
	 *
	 * @return EntityUtils Istanza della classe EntityUtils
	 */

	static function getInstance()
	{
        if (self::$istance == null)
		{
            self::$istance = new EntityUtils();
        }

        return self::$istance;
    }

	public function loadEntity($entity, $array)
	{
		foreach ($array as $name => $value)
		{
			$method_name = "set".ucfirst($name);

			if (method_exists($entity, $method_name))
				call_user_func_array(array($entity, $method_name), array($value));
		}

		return $entity;
	}

	public function fillEntity($entity, $array)
	{
		foreach ($array as $column => $value)
		{
			$entityVars = $entity->_getVarsFromColumn();

			if(isset($entityVars[$column]))
			{
				$method_name = "set".ucfirst($entityVars[$column]);

				if (method_exists($entity, $method_name))
					call_user_func_array(array($entity, $method_name), array($value));
			}
		}

		return $entity;
	}

	public function fillCustomEntity($entity, $array)
	{
		foreach ($array as $column => $value)
		{
			$explodeColumn = explode("_", $column);

			$nameVal = $explodeColumn[0];

			for ($i = 1; $i < count($explodeColumn); $i++)
				$nameVal .= ucfirst($explodeColumn[$i]);

			$entity->$nameVal = $value;
		}

		return $entity;
	}

	public function mergeTwoEntity(Entity $EntityFrom, Entity $EntityTo)
	{
		foreach($EntityFrom->_getVars() as $fieldName => $fieldValue)
		{
			$methodName = "get" . ucfirst($fieldName);
			@call_user_func_array(array($EntityTo, "set" . ucfirst($fieldName)), array($EntityFrom->$methodName()));
		}

		return $EntityTo;
	}
}
?>
